#pragma comment (lib, "ws2_32.lib")

#include "stdafx.h"
#include <windows.h>
#include <winsock.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
//#include <winsock2.h>

#define DEST_PORT 80
#define BUFSIZE 1000
#define DEST_IP "87.248.113.14"

using namespace std;

char buffer[BUFSIZE];

void parseHTML()
{	
	//parse anything after img src ending with "
	

}

char* getIP(char* hostname)
{
	struct hostent *ht = 0;

	if ((ht=gethostbyname(hostname)) == NULL)
	{
		cout << "gethostbyname failed";
		exit(1);
    }
	return(ht->h_addr);
}

int main(int argc, char **argv)
{	
	WSADATA WSAData;

	FILE* offsoc = NULL;
	FILE* tosoc = NULL;
	ofstream HTML("HTML.txt");

	int sockfd;
	char* host = argv[1];
    struct sockaddr_in dest_addr;   // will hold the destination addr
	
	// Initialize winsock dll
	if(WSAStartup(MAKEWORD(1, 0), &WSAData) != 0)
	{
		cout << "error in wsa\n";
		exit(1);
	}

	//cleaning the winsock library, error checking
	/*if (WSACleanup() != 0)
	{
		cout << "WSACleanup failed \n";
		exit(1);
	}*/

    sockfd = socket(PF_INET, SOCK_STREAM, 0); // do some error checking!

    dest_addr.sin_family = AF_INET;          // host byte order
    dest_addr.sin_port = htons(DEST_PORT);   // short, network byte order
    dest_addr.sin_addr = *((struct in_addr *)(getIP(host)));
    //dest_addr.sin_addr.s_addr = inet_addr(DEST_IP);

	memset(dest_addr.sin_zero, '\0', sizeof dest_addr.sin_zero);

    if(connect(sockfd, (struct sockaddr *)&dest_addr, sizeof dest_addr) == -1)
	{
		cout << "connect error";
        exit(1);
    }
	else{ cout << "connected\n"; }

	cout << "error\n";
	cout << "sockfd = " << _fdopen(1960, "w");
    
	char *msg = "GET / HTTP/1.0\n\n";
	int len = strlen(msg);
	int bytes = send(sockfd, msg, len, 0); 

	//Try to connect to socket
	if((tosoc = _fdopen(sockfd, "w")) == NULL)
	{
       perror("Could not open file stream on supplied file descriptor");
       exit(1);
    }
	else{ cout << "Done fdopen=w\n"; }

	if((offsoc = _fdopen(sockfd, "r")) == NULL)
	{
       cout << "Could not open file stream on supplied file descriptor";
       exit(1);
    }
	else{ cout << "Done fdopen=r\n"; }
	
	//Get data
	fprintf(tosoc, "GET / HTTP/1.0\n\n"); //mymessage is the get request
	fflush(tosoc);

	char *s = fgets(buffer, BUFSIZE-1, offsoc);
	for(int i = 1; s != NULL; i++)
	{
		printf("%s", buffer);
		HTML << buffer;
		s = fgets(buffer, BUFSIZE-1, offsoc);
	}
	
	//close connections
	fclose(offsoc);
	fclose(tosoc);
	closesocket(sockfd);
	HTML.close();
	// Shutdown Winsock
    WSACleanup();

    return 0;
}
